<?php

namespace app\service\encryption;

class Aes
{
    protected $key;
    protected $iv;
    public function __construct()
    {
        $this->key="key123";
        $this->iv="iv34567890123456";
    }

    /**
     * AES加密
     */
    public function encrypt($array = [], $method = 'AES-128-CBC')//AES-256-CBC
    {
        $key =$this->key;
        $iv =$this->iv;
        $plaintext = json_encode($array, JSON_UNESCAPED_UNICODE);
        $str       = openssl_encrypt($plaintext, $method, $key, 0, $iv);

        return bin2hex(base64_decode($str));
    }

    /**
     * AES解密
     */
    public function decrypt($encrypt = '', $method = 'AES-128-CBC')//AES-256-CBC
    {
        $encrypt = base64_encode(hex2bin($encrypt));
        $key =$this->key;
        $iv =$this->iv;
        $str = openssl_decrypt($encrypt, $method, $key, OPENSSL_ZERO_PADDING, $iv);
        $str = substr($str, 0, strrpos($str, "}") + 1);
        return json_decode($str, true);
    }
}
